package com.github.admin.edu.security.jwt.server.interceptor;

import com.github.admin.edu.assembly.common.util.ObjectUtil;
import com.github.admin.edu.assembly.exception.auth.ClientTokenException;
import com.github.admin.edu.assembly.string.util.StringUtils;
import com.github.admin.edu.security.jwt.common.service.JWTInformation;
import com.github.admin.edu.security.jwt.common.service.RsaKeyHelper;
import com.github.admin.edu.security.jwt.common.util.JWTUtil;
import com.github.admin.edu.security.jwt.server.entity.TSysOauthManage;
import com.github.admin.edu.security.jwt.server.service.JWTSysOauthManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-7-19
 */
public class ClientAuthInterceptor extends HandlerInterceptorAdapter {

    /**
     * 自定义头 名称
     */
    @Value("${server.custom.token.header.token-header}")
    private String tokenHeader;
    @Value("${server.custom.token.header.client-id}")
    private String clientId;

    @Autowired
    private JWTSysOauthManageService service;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String token=request.getHeader(tokenHeader);
        String client_Id=request.getHeader(clientId);
        if(StringUtils.isNotBlank(token)&&StringUtils.isNotBlank(client_Id)){
            TSysOauthManage oauthManage=service.getAllByCode(client_Id);
            if(null!=oauthManage){
                try {
                    JWTInformation information=JWTUtil.getInfoFromToken(token,RsaKeyHelper.generatePublicKey(oauthManage.getPassword()));
                    if(null!=information&&information.getId().equals(client_Id)){
                        //TODO:: 后期添加服务授权，对服务调用者进行权限判断！
                        return true;
                    }
                }catch (Exception e){
                    throw new ClientTokenException(" You do not have permission to access secondary services !!!!!! ");
                }

            }

        }
        throw  new ClientTokenException("token is not find !!!!!! ");
    }
}
